package com.fanfan.shiroadmin.modules.sys.service.impl;

import com.fanfan.shiroadmin.common.exception.ServiceRuntimeException;
import com.fanfan.shiroadmin.common.utils.RedisKeysUtil;
import com.fanfan.shiroadmin.common.utils.RedisUtil;
import com.fanfan.shiroadmin.common.utils.ValidateUtil;
import com.fanfan.shiroadmin.modules.sys.service.ICaptchaService;
import com.google.code.kaptcha.Producer;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;

/**
 * 获得验证码服务
 * @author DunFan.Liao
 * @date 2021/8/19 17:50
 */
@Service(ICaptchaService.BEAN_ID)
@Log4j2
public class CaptchaServiceImpl implements ICaptchaService
{

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private Producer producer;

    /**
     * namespace redis基础数据缓存的命名空间
     */
    @Value("${redis.namespace}")
    private  String namespace;
    @Override
    public BufferedImage getCaptcha(String uuid)
    {
        if (!ValidateUtil.isNullOrEmpty(uuid)){
            //生成文字验证码
            String code = producer.createText();
            // 将uuid存入redis,设置一分钟有效期
            String key = RedisKeysUtil.getCaptchaKey(namespace,uuid);
            redisUtil.set(key,code,60);
            return producer.createImage(code);
        }else
        {
            throw new ServiceRuntimeException("uuid不能为空");
        }
    }

    @Override
    public boolean validateCaptcha(String uuid,String code)
    {
        if (ValidateUtil.isNullOrEmpty(uuid)){
            // 查询redis中是否有有效的uuid
            String key = RedisKeysUtil.getCaptchaKey(namespace,uuid);
            String captcha = redisUtil.get(key);
            if (ValidateUtil.isNullOrEmpty(captcha)) {
                throw new ServiceRuntimeException("验证码已过期，请重新输入");
            }
            return captcha.equals(code);

        }else
        {
            throw new ServiceRuntimeException("uuid不能为空");
        }
    }
}
